<template>
  <div class="medication-container">
    <div class="vertical-warning">健康体检是预防疾病的第一道防线</div>
    <h3><i class="fas fa-stethoscope"></i> 体检报告</h3>
    <div v-if="isSampleData" class="sample-notice">
      <el-icon>
        <info-filled/>
      </el-icon>
      当前显示为示例数据，请登录后查看真实记录
    </div>


    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button
          v-if="!editMode"
          type="primary"
          @click="editMode = true"
          icon="el-icon-edit"
          class="action-btn"
      >编辑
      </el-button>
      <el-button
          v-if="!editMode"
          type="success"
          @click="addNewHistory"
          icon="el-icon-plus"
          class="action-btn"
      >新增
      </el-button>
      <el-button
          v-if="!editMode"
          type="warning"
          @click="toggleSort"
          icon="el-icon-sort"
          class="action-btn"
      >{{ sortButtonText }}
      </el-button>
      <template v-else>
        <el-button
            type="success"
            @click="saveChanges"
            icon="el-icon-check"
            class="confirm-btn"
        >保存
        </el-button>
        <el-button
            type="danger"
            @click="cancelEdit"
            icon="el-icon-close"
            class="cancel-btn"
        >取消
        </el-button>
      </template>
    </div>

    <div class="medication-list">
      <div 
        class="medication-card"
        :class="{ 'sample-data': isSampleData }"
        v-for="(report, index) in checkupReports"
        :key="report.recordId || index"
      >
        <div class="medication-header">
          <span class="detail-label"><i class="far fa-id-card"></i> ID:{{ report.recordId }}</span>
          <div class="checkup-status" v-if="!editMode">
            <i class="far fa-calendar-alt"></i> {{ report.recordDate }}
          </div>
        </div>

        <div class="medication-details">
          <div class="detail-row">
            <span class="detail-label"><i class="fas fa-exclamation-triangle"></i> 异常指标:</span>
            <pre v-if="!editMode">{{ report.abnormalIndicators }}</pre>
            <el-input
              v-else
              v-model="report.abnormalIndicators"
              type="textarea"
              :rows="3"
              placeholder="请输入异常指标"
            />
          </div>

          <div class="detail-row">
            <span class="detail-label"><i class="fas fa-diagnoses"></i> 病情分析:</span>
            <span v-if="!editMode">{{ report.condition }}</span>
            <el-input
              v-else
              v-model="report.condition"
              type="textarea"
              :rows="2"
              placeholder="请输入病情分析"
            />
          </div>

          <div class="detail-row">
            <span class="detail-label"><i class="fas fa-comment-medical"></i> 医嘱:</span>
            <span v-if="!editMode">{{ report.medicalAdvice }}</span>
            <el-input
              v-else
              v-model="report.medicalAdvice"
              type="textarea"
              :rows="3"
              placeholder="请输入医嘱"
            />
          </div>

          <div class="detail-row">
            <span class="detail-label"><i class="fas fa-hospital"></i> 体检机构:</span>
            <span v-if="!editMode">{{ report.examinationInstitution }}</span>
            <el-input
              v-else
              v-model="report.examinationInstitution"
              :rules="[{ required: true, message: '请输入体检机构名称' }]"
              placeholder="请输入体检机构"
            />
          </div>

          <div class="detail-row">
            <span class="detail-label"><i class="fas fa-user-md"></i> 体检医生:</span>
            <span v-if="!editMode">{{ report.examinationDoctor }}</span>
            <el-input
              v-else
              v-model="report.examinationDoctor"
              :rules="[{ required: true, message: '请输入体检医生姓名' }]"
              placeholder="请输入体检医生"
            />
          </div>
        </div>


        <!-- 删除按钮放在每张卡片内 -->
        <div class="card-actions" v-if="editMode">
          <el-button
              type="danger"
              size="small"
              @click="deleteHandler(index)"
              icon="el-icon-delete"
          >删除
          </el-button>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-controls">
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="totalRecords"
          :page-sizes="[1,2,4,8,10, 20, 30, 50]"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"


          @current-change="handlePageChange"
      />
    </div>

    <!-- 升级后的弹出对话框 -->
    <div class="popup-container" :class="{ 'show-popup': showAddDialog }">
      <div class="popup-backdrop" @click="showAddDialog = false"></div>
      <div class="popup-dialog" :class="{ 'scale-in': showAddDialog }">
        <div class="popup-header">
          <div class="popup-title">
            <i class="fas fa-plus-circle header-icon"></i>
            <h3>新增体检报告</h3>
          </div>
          <button class="close-button" @click="showAddDialog = false">
            <i class="el-icon-close"></i>
          </button>
        </div>
      <el-form :model="currentReport" label-width="100px">
        <el-form-item label="体检机构" prop="examinationInstitution" >
          <el-input v-model="currentReport.examinationInstitution" />
        </el-form-item>
        <el-form-item label="体检医生" prop="examinationDoctor" >
          <el-input v-model="currentReport.examinationDoctor" />
        </el-form-item>
        <el-form-item label="异常指标" prop="abnormalIndicators">
          <el-input v-model="currentReport.abnormalIndicators" type="textarea" :rows="3" placeholder="请输入异常指标"/>
        </el-form-item>
        <el-form-item label="病情分析" prop="condition">
          <el-input v-model="currentReport.condition" type="textarea" :rows="2" placeholder="请输入病情分析"/>
        </el-form-item>
        <el-form-item label="医嘱" prop="medicalAdvice">
          <el-input v-model="currentReport.medicalAdvice" type="textarea" :rows="3" placeholder="请输入医嘱"/>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="currentReport.remarks"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <div class="popup-footer">
        <el-button
            class="custom-cancel-btn"
            @click="showAddDialog = false"
        >取消
        </el-button>
        <el-button
            type="primary"
            class="custom-confirm-btn"
            @click="saveNewCheckup"
        >保存记录
        </el-button>
      </div>

    </div>

    </div>
    <div class="total-records-notice">
      <el-icon>
        <info-filled/>
      </el-icon>
      您共有{{ totalRecords }}份体检报告
    </div>

  </div>
</template>


<script setup>
import {reactive, ref, onMounted, nextTick, computed} from 'vue';
import { createHealthRecord, deleteHealthRecord, getCheckupReports, updateHealthRecord } from '@/api/profile.js';
import {ElButton, ElMessage, ElMessageBox, ElPagination} from 'element-plus';
import {InfoFilled} from "@element-plus/icons-vue";
import {postLog} from "@/api/log.js"

const checkupReports = ref([]);
const currentReport = reactive({
  recordType: '体检报告',
  abnormalIndicators: '',
  condition: '',
  medicalAdvice: '',
  examinationInstitution: '',
  examinationDoctor: '',
  remarks: '' // 新增备注字段
});

const isSortedAscending = ref(true);
const sortButtonText = computed(() => isSortedAscending.value ? '按日期排序 ↑' : '按日期排序 ↓');

// 共用状态
const editMode = ref(false);
const showAddDialog = ref(false);
const currentPage = ref(1);
const pageSize = ref(8);
const totalRecords = ref(0);
const userInfo = ref(null);
const originalMedications = ref([]);

const storedUser = localStorage.getItem('currentUser');
userInfo.value = storedUser ? JSON.parse(storedUser) : null;
// 获取体检报告数据
const loadCheckupData = async () => {
  try {

    const res = await getCheckupReports(userInfo.value?.id, {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });
    isSortedAscending.value = !isSortedAscending.value;
    res.data.data.sort((a, b) => {
      return isSortedAscending.value
          ? a.recordDate.localeCompare(b.recordDate)
          : b.recordDate.localeCompare(a.recordDate);
    });
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    checkupReports.value = res.data.data.slice(startIndex, endIndex);
    originalMedications.value = JSON.parse(JSON.stringify(res.data.data));

    totalRecords.value = res.data.data.length;
  } catch (error) {
    ElMessage.error('获取数据失败');
  }
};



// 删除记录
const deleteHandler = async (index) => {
  try {
    await ElMessageBox.confirm('确定删除该体检报告？');
    await deleteHealthRecord(checkupReports.value[index].recordId);
    checkupReports.value.splice(index, 1);

    checkupReports.value.splice(index, 1);
    ElMessage.success('删除成功');
    if (checkupReports.value.length === 0 && currentPage.value > 1) {
      currentPage.value--;
      await load();
    }
    if (userInfo.value && recordId) {
      await postLog({
        id: userInfo.value.id,
        role: userInfo.value.role,
        username: userInfo.value.username,
        ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
        loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
        recordType: '体检报告',
        action: '删除',
        recordId: recordId,
        logTime: new Date().toISOString() // 添加 logTime 属性
      });
    }
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败：' + error.message);

  }
};

// 完善分页处理
const handlePageChange = (newPage) => {
  isSortedAscending.value = !isSortedAscending.value;

  currentPage.value = newPage;
  loadCheckupData();
};

// 初始化加载数据
onMounted(() => {

    loadCheckupData();

});

const addNewHistory = () => {
  console.log('新增按钮点击事件触发');
  Object.assign(currentReport, {
    recordId: null,
    recordDate: new Date().toISOString().split('T')[0],
    recordType: '体检报告',
    abnormalIndicators: '',
    condition: '',
    medicalAdvice: '',
    examinationInstitution: '',
    examinationDoctor: '',
    remarks: '' // 新增备注字段
  });

  // 触发对话框显示并添加动画类
  nextTick(() => {
    showAddDialog.value = true;
  });
};

// 新增记录保存方法
const saveNewCheckup = async () => {
  try {
    const response= await createHealthRecord(userInfo.value?.id,{
      ...currentReport,
      detail: `${currentReport.abnormalIndicators}|${currentReport.condition}|${currentReport.medicalAdvice}|${currentReport.examinationInstitution}|${currentReport.examinationDoctor}|${currentReport.remarks}|`  });
    showAddDialog.value = false;
    ElMessage.success('新增成功');
    // 新增成功后刷新数据
    await loadCheckupData();

    //新增日志记录
    if (userInfo.value) {
      await postLog({
        id: userInfo.value.id,
        role: userInfo.value.role,
        username: userInfo.value.username,
        ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
        loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
        recordType: '体检报告',
        action: '增加',
        recordId: response.data?.data,
        logTime: new Date().toISOString() // 添加 logTime 属性
      });
    }

  } catch (error) {
    ElMessage.error('保存失败');
  }
};
const cancelEdit = () => {
  editMode.value = false;
  checkupReports.value = JSON.parse(JSON.stringify(originalMedications.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)));
  };
// 保存修改
const saveChanges = async () => {
  try {
    const promises = checkupReports.value.map(async (currentReport) => {

    await updateHealthRecord({
      recordId: currentReport.recordId,
      recordDate: currentReport.recordDate,
      recordType: '体检报告',
      detail: `${currentReport.abnormalIndicators}|${currentReport.condition}|${currentReport.medicalAdvice}|${currentReport.examinationInstitution}|${currentReport.examinationDoctor}|${currentReport.remarks}|`  });
    });
    await Promise.all(promises);
    ElMessage.success('保存成功');
    editMode.value = false;
    await loadCheckupData();
    // 修改操作日志记录
    if (userInfo.value) {
      for (const med of medications.value) {
        await postLog({
          id: userInfo.value.id,
          role: userInfo.value.role,
          username: userInfo.value.username,
          ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
          loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
          recordType: '体检报告',
          action: '修改',
          recordId: med.recordId,
          logTime: new Date().toISOString() // 添加 logTime 属性
        });
      }
    }
  } catch (error) {
    ElMessage.error('保存失败');
  }
};


const toggleSort = () => {
  loadCheckupData();
};
const handleSizeChange = (val) =>{
  currentPage.value=1;
  pageSize.value = val;
  loadCheckupData();
}
</script>
<style scoped>
@import "@/assets/css/new.css";
</style>